package base

/*************************************************
 *	@author zander
 *	@time 	2018年2月3日14:43:37
 *	@brief 	gin路由控制器
 *************************************************/

import (
	"io/ioutil"
	"bytes"
	"time"
	//"gitee.com/dayu1985/framework/storage/cache"
	cache "gitee.com/dayu1985/framework/storage/cache/cache_leveldb"
	"gitee.com/dayu1985/framework/net/web/jwt"
	"gitee.com/dayu1985/can_api/service"
	"github.com/gin-gonic/gin"
)

//所有请求的入口权限设置
//1. 基板APP未授权接口
//2. 基板APP授权接口
type Privilege struct {
	Public          *gin.RouterGroup
	App             *gin.RouterGroup
	AppAuth         *gin.RouterGroup
	AppThird        *gin.RouterGroup
	AppResource     *gin.RouterGroup
	AppResourceAuth *gin.RouterGroup
	JWT             *jwt.GinJWT
}

func initBodyData(c *gin.Context, data []byte) {
	//模拟一个数据流，然后放到body中
	s := bytes.NewReader(data)
	r := ioutil.NopCloser(s)
	r.Close()
	c.Request.Body = r
}

func resouAuth(c *gin.Context) {
	c.Next()
}

//**************************所有请求的入口**********************
var sysService *service.SysService

func baseAuth(ctx *gin.Context) {
	////1. 读取请求中的appid
	//app := ctx.GetHeader("APP")
	////3. 判断是否为空
	//if app == "" {
	//	Fail(ctx, errors.AuthAppIdNilErr())
	//	ctx.Abort()
	//	return
	//}
	////4. 读取库中的app应用信息
	//if sysService == nil {
	//	sysService = service.NewSysService()
	//}
	////5. 比较
	//if app != "BXCB" && app != *sysService.GetApp().ID {
	//	Fail(ctx, errors.AuthAppNotFoundErr())
	//	ctx.Abort()
	//	return
	//}
	ctx.Next()
}

// 实例化路由控制器
func NewPrivilege(engine *gin.Engine) *Privilege {
	p := Privilege{}
	//资源文件路由
	p.AppResource = engine.Group("/app/resource")
	p.Public = engine.Group("/")

	engine.Use(baseAuth)
	cacher := cache.NewLevelCacheOpenFile("./levelcache")
	au := jwt.NewGinJWT(30*24*time.Hour, "HDKJ1234!", cacher)
	//初始化jwt
	p.JWT = au
	//APP端匿名权限路由
	p.App = engine.Group("/app")
	//资源文件权限路由
	p.AppResourceAuth = engine.Group("/app/resource", resouAuth)

	return &p
}

// 实例化所有的实现的接口
func Route(routeContext *RouteContext) {
	for _, route := range routers {
		route(routeContext)
	}
}

func getBodyData(c *gin.Context) ([]byte) {
	data, err := ioutil.ReadAll(c.Request.Body)
	if err != nil {
		panic(err)
	}
	return data
}
